package org.ansel.webnodb.demo.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class AnselHttpsClientUtil {
	public static void main (String[] args) {
		AnselHttpsClientUtil httpsclient = new AnselHttpsClientUtil();
		try {
			String ret = httpsclient.httpget("https://api.ip.sb/geoip");//http://ip-api.com/json/     https://api.ip.sb/geoip
			System.out.println(ret);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String httpget(String uri) throws Exception{
		if (uri.startsWith("https://")) {
			return this.httpsget(uri);
		}
		URL url = new URL(uri);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0");
		conn.setDoInput(true);// 打开输入流，以便从服务器获取数据
		conn.setDoOutput(true);// 打开输出流，以便向服务器提交数据
		BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		String line;
		StringBuffer rt = new StringBuffer();
		while ((line = in.readLine()) != null) {
			rt.append(line);
		}
		return rt.toString();
	}
	public String httpsget(String uri) throws IOException, UnrecoverableKeyException, CertificateException, KeyStoreException, KeyManagementException, NoSuchAlgorithmException, NoSuchProviderException {
		// 创建SSLContext对象，并使用我们指定的信任管理器初始化
		TrustManager[] tm = { getTrustManagers() };
		SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
		sslContext.init(null, tm, new java.security.SecureRandom());
		// 从上述SSLContext对象中得到SSLSocketFactory对象
		javax.net.ssl.SSLSocketFactory ssf = sslContext.getSocketFactory();
		URL url = new URL(uri);
		HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection();
		httpsConn.setSSLSocketFactory(ssf);
		httpsConn.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0");
		httpsConn.setDoInput(true);// 打开输入流，以便从服务器获取数据
		httpsConn.setDoOutput(true);// 打开输出流，以便向服务器提交数据
//		httpsConn.setRequestMethod("POST");
		//TODO by zj 根据https://blog.csdn.net/qq_16957817/article/details/109205773设置post参数
//		httpsConn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");//application/x-www-form-urlencoded, 
		BufferedReader in = new BufferedReader(new InputStreamReader(httpsConn.getInputStream()));
		String line;
		StringBuffer rt = new StringBuffer();
		while ((line = in.readLine()) != null) {
			rt.append(line);
		}
		return rt.toString();
    }

    // 忽略服务器端证书链的认证
    private static TrustManager getTrustManagers() {
        return new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        };
    }

}
